using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace Games.Frameworks.UIParticle
{
    [ExecuteAlways]
    public class UIParticleManager : MonoBehaviour
    {
        #region Mono单例
        //单例
        //protected static bool _isDestroied;
        protected static UIParticleManager m_instance;

        public static UIParticleManager instance
        {
            get
            {
                if (!m_instance)
                {
                    m_instance = FindObjectOfType<UIParticleManager>();
                    if (m_instance == null)
                    {
                        var go = new GameObject(typeof(UIParticleManager).Name);
                        m_instance = go.AddComponent<UIParticleManager>();
                        go.hideFlags = HideFlags.DontSave;
                        /*var parent = MonoSingletonHelper.GetRoot();
                        if (parent != null)
                        {
                            go.transform.SetParent(parent.transform);
                        }*/
                    }
                }
                return m_instance;
            }
        }
        protected  void Awake()
        {
            // 已经有实例存在了，删除新的
            if (m_instance != null && m_instance != this) {
                var scriptName = name;
                var gameObjectName = gameObject.name;
                Debug.LogWarning($"MonoSingleton is duplicated, gameobject name [{gameObjectName}], script name [{scriptName}]");
                enabled = false;
                gameObject.SetActive(false);
                Destroy(gameObject);
                StopAllHelpers();
                return;
            }
            
            if (m_instance == null)
            {
                m_instance = this;
            }

            if(Application.isPlaying)
                DontDestroyOnLoad(gameObject);
            CheckInit();
        }
        
        protected virtual void OnDestroy()
        {
            if (m_instance != null && m_instance == this) {
                m_instance = null;
                //_isDestroied = true;   
            }
        }
        #endregion
        
        private static Stack<UIParticleHelper> helpersStack = new Stack<UIParticleHelper>();
        public static int nowMaxHelperId=0;
        private bool beforeBeginClear=false;//开始游戏前需要首先清空
        private bool afterEndClear=false;//结束游戏后需要首先清空
        public void CheckInit()
        {
            if (Application.isPlaying&&!beforeBeginClear)
            {
                beforeBeginClear = true;
                afterEndClear = false;
                StopAllHelpers();
            }
            else if(!Application.isPlaying&&!afterEndClear)
            {
                afterEndClear = true;
                beforeBeginClear = false;
                StopAllHelpers();
            }
        }

        //播放粒子
        public UIParticleHelper ParticlePlay(UIParticle uiParticle)
        {
            CheckInit();
            var helper = GetUIParticleHelper();
            helper?.Play(uiParticle);
            return helper;
        }
        
        //取到一个空闲的UIParticleHelper
        public UIParticleHelper GetUIParticleHelper()
        {
            if (helpersStack.Count > 0)
            {
                var helper = helpersStack.Pop();
                Debug.Log("得到的HelperID："+helper.Id+"剩余数量："+helpersStack.Count);
                return helper;
            }

            return NewParticleHelper();
        }
        
        /// <param name="pause">暂停但不是直接停止</param>
        public void ParticleStop(UIParticleHelper helper,bool pause=false)
        {
            if(helper==null)
                Debug.LogError("你想回收的Particle录制设备为空！无法回收！");
            if (helper.use)
            {
                helper.Stop(pause);
                helpersStack.Push(helper);
            }
            else
            {
                if (helpersStack.FirstOrDefault(o => o == helper) == null)
                {
                    Debug.LogWarning("有一个未播放且未回收的Particle录制设备：现已被回收");
                    helpersStack.Push(helper);
                }
            }
        }

        //在Editor界面下修改完毕后调用
        public void EditorComplete(UIParticleHelper helper)
        {
            if(helper==null)
                Debug.LogError("你想回收的Particle录制设备为空！无法回收！");
            if (helper.use)
            {
                helper.EditorComplete();
                helpersStack.Push(helper);
            }
            else
            {
                if (helpersStack.FirstOrDefault(o => o == helper) == null)
                {
                    Debug.LogWarning("有一个未播放且未回收的Particle录制设备：现已被回收");
                    helpersStack.Push(helper);
                }
            }
        }

        private UIParticleHelper NewParticleHelper()
        {
            /*string uniqueName = GameObjectUtility.GetUniqueNameForSibling(transform, "ParticleHelper");
            var helperObj = new GameObject(uniqueName);
            helperObj.transform.SetParent(transform);
            var helper = helperObj.AddComponent<UIParticleHelper>();
            
            var cameraObj = new GameObject("Camera");
            cameraObj.transform.SetParent(helperObj.transform);
            helperObj.AddComponent<Camera>();
            
            var particleObj = new GameObject("Particle System");
            particleObj.transform.SetParent(helperObj.transform);
            helperObj.AddComponent<ParticleSystem>();*/
            var res=Resources.Load<GameObject>("UIParticleHelper");
            GameObject helperObj = Instantiate(res, transform);
            var helper=helperObj.GetComponent<UIParticleHelper>();
            res.hideFlags = HideFlags.DontSave;
            return helper;
        }

        private void OnEnable()
        {
            gameObject.hideFlags = HideFlags.DontSave;
        }

        public void ResetStack()
        {
            helpersStack.Clear();
            var helpers = GetComponentsInChildren<UIParticleHelper>();
            nowMaxHelperId = helpers.Length;
            foreach (var h in helpers)
            {
                if (!h.use)
                {
                    helpersStack.Push(h);
                }
            }
        }

        public void StopAllHelpers()
        {
            helpersStack.Clear();
            var helpers = GetComponentsInChildren<UIParticleHelper>();
            nowMaxHelperId = helpers.Length;
            foreach (var h in helpers)
            {
                h.Stop();
                helpersStack.Push(h);
            }
            Debug.Log("回收完毕 栈中个数："+helpersStack.Count);
        }

    }
}

